package com.aliyuncs.aui.service.impl;

import com.aliyuncs.aui.common.utils.MySQLUtil;
import com.aliyuncs.aui.dto.res.SessionResponse;
import com.aliyuncs.aui.dto.res.CommonResponse;
import com.aliyuncs.aui.service.SessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

@Service
public class SessionServiceImpl implements SessionService {
    private static final Logger log = LoggerFactory.getLogger(SessionServiceImpl.class);
    private final MySQLUtil mySQLUtil;

    public SessionServiceImpl(MySQLUtil mySQLUtil) {
        this.mySQLUtil = mySQLUtil;
    }

    @Override
    public CommonResponse generateSessionUuid() {
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();

        return CommonResponse.builder()
                .result(true)
                .message(uuidStr)
                .build();
    }

    @Override
    public CommonResponse createSession(String sessionId, String type, String role, String logContent, String tenantId, String userId) {
        if (userId == null || userId.isEmpty()) {
            userId = "system";
        }
        String sql = "INSERT INTO session (session_id, type, role, log, created_at, user_id, tenant_id) VALUES (?, ?, ?, ?, NOW(), ?, ?)";
        
        try {
            int affectedRows = mySQLUtil.executeUpdate(sql, sessionId, type, role, logContent, userId, tenantId);
            if (affectedRows > 0) {
                return CommonResponse.builder()
                        .result(true)
                        .message("Session created successfully")
                        .build();
            }
            return CommonResponse.builder()
                    .result(false)
                    .message("Failed to create session")
                    .build();
        } catch (SQLException e) {
            log.error("Create session failed", e);
            return CommonResponse.builder()
                    .result(false)
                    .message("Database error: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public SessionResponse getSession(String sessionId, String type) {
        String sql = "SELECT role, log, created_at FROM session WHERE session_id = ? AND type = ? ORDER BY created_at ASC";
        try (ResultSet resultSet = mySQLUtil.executeQuery(sql, sessionId, type)) {
            if (resultSet.next()) {
                return SessionResponse.builder()
                        .role(resultSet.getString("role"))
                        .log(resultSet.getString("log")) 
                        .created_at(resultSet.getString("created_at"))
                        .build();
            }
            return null;
        } catch (SQLException e) {
            log.error("Get session failed", e);
            return null;
        }
    }
}
